package com.sgb.kjwl.view.ui.adapter.self.logistics;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.R;
import com.sgb.kjwl.model.entity.self.OrderQuoteEntity;
import com.sgb.kjwl.utils.LonLatUtils;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.transport.BiddingOrderDetailsActivity;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.recyclerview.adapter.ItemViewHolder;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;

import java.util.List;

/**
 * Describe:     报价单位——货主视角适配器(竞价货源)
 * Author:  yangLei
 * Date:    2021/8/31
 */
public class OfferOwnerAdapter3 extends BaseRecycleAdapter<OrderQuoteEntity> {

    private OnTabClickListener onTabClickListener;
    private Context context;

    public OfferOwnerAdapter3(Context context, List<OrderQuoteEntity> data) {
        super(context, R.layout.item_offer_owner_map_list, data);
        this.context = context;
    }

    public interface OnTabClickListener {
        void onAgreeClick(OrderQuoteEntity entity);

        void onChat(String account);

    }

    public void setOnTabClickListener(OnTabClickListener onTabClickListener) {
        this.onTabClickListener = onTabClickListener;
    }

    @Override
    public void convert(ItemViewHolder holder, OrderQuoteEntity entity) {
        TextView owner_name = holder.getItem().findViewById(R.id.owner_name);
        TextView freight_offer = holder.getItem().findViewById(R.id.freight_offer);
        ImageView car_iv = holder.getItem().findViewById(R.id.car_iv);
        TextView car_info = holder.getItem().findViewById(R.id.car_info);
        TextView position_info = holder.getItem().findViewById(R.id.position_info);
        TextView loading_distance = holder.getItem().findViewById(R.id.loading_distance);
        LinearLayout distance_bar = holder.getItem().findViewById(R.id.distance_bar);
        TextView offer_status = holder.getItem().findViewById(R.id.offer_status);
        TextView view_order = holder.getItem().findViewById(R.id.view_order);
        TextView right_btn = holder.getItem().findViewById(R.id.right_btn);
        TextView price_hint = holder.getItem().findViewById(R.id.price_hint);
        TextView unit_hint = holder.getItem().findViewById(R.id.unit_hint);
        TextView address_hint = holder.getItem().findViewById(R.id.address_hint);
        LinearLayout exchange_tab = holder.getItem().findViewById(R.id.exchange_tab);
        LinearLayout call_phone_tab = holder.getItem().findViewById(R.id.call_phone_tab);
        RelativeLayout handle_layout = holder.getItem().findViewById(R.id.handle_layout);
        LinearLayout car_info_layout = holder.getItem().findViewById(R.id.car_info_layout);
        LinearLayout predict_arrive_lay = holder.getItem().findViewById(R.id.predict_arrive_lay);
        TextView predict_arrive_time = holder.getItem().findViewById(R.id.predict_arrive_time);
        View line_view = holder.getItem().findViewById(R.id.line_view);

        handle_layout.setVisibility(View.VISIBLE);
        line_view.setVisibility(View.VISIBLE);
        predict_arrive_lay.setVisibility(View.VISIBLE);

        //预计到场时间
        if (entity.getInTime() != null && entity.getInTime() > 0) {
            predict_arrive_time.setText(DateUtils.stampToDay5(entity.getInTime()));
        } else {
            predict_arrive_time.setText("/");
        }

        /*运费报价*/
        if (!TextUtils.isEmpty(entity.getFreight())) {
            freight_offer.setText(NumberUtil.trim0(entity.getFreight()) + "元/吨");
            if (!TextUtils.isEmpty(entity.getSourceFreight())) {
//                freight_offer.setTextColor(Double.parseDouble(entity.getFreight()) > Double.parseDouble(entity.getSourceFreight())
//                        ? context.getResources().getColor(R.color.color_FF4B10) : context.getResources().getColor(R.color.color_secondary_yellow));
                car_iv.setVisibility(View.VISIBLE);
            } else {
                car_iv.setVisibility(View.GONE);
            }
        } else {
            freight_offer.setText("/");
        }

        /*距离*/
        double distance = 0.0d;
        if (!TextUtils.isEmpty(entity.getDistance())) {
            distance = Double.parseDouble(entity.getDistance());
        } else if (entity.getLongitude() != null && entity.getLongitude() > 0
                && entity.getLatitude() != null && entity.getLatitude() > 0) {
            distance = LonLatUtils.getDistance(entity.getLongitude(), entity.getLatitude(),
                    NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "")),
                    NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, ""))
            );
        }
        if (distance <= 0) {
            loading_distance.setText("");
            distance_bar.setVisibility(View.GONE);
        } else {
            loading_distance.setText("距装货地 " + (distance < 1 ? "1km以内" : StringUtil.formatUpDistance(String.valueOf(distance)) + "km"));
            distance_bar.setVisibility(View.VISIBLE);
        }

        int offerOrReceive = entity.getIsVoluntarily();
        right_btn.setText("下单");
        if (offerOrReceive == 2) {
            price_hint.setText("接单运费");
            unit_hint.setText("接单车主");
        } else {
            price_hint.setText("运费报价");
            unit_hint.setText("报价车主");
        }

        exchange_tab.setVisibility(View.VISIBLE);
        exchange_tab.setOnClickListener(v -> gotoExchange(entity));
        call_phone_tab.setVisibility(View.VISIBLE);
        call_phone_tab.setOnClickListener(v -> checkCanCall(entity));

        //报价状态：2.0.8  报价状态：offerStatus     1已报价  2已同意  5货主未同意
        switch (entity.getOfferStatus()) {
            //待确认
            case "1":
                right_btn.setVisibility(View.VISIBLE);
                view_order.setVisibility(View.GONE);
                offer_status.setText("");
                break;

            //已同意
            case "2":
                right_btn.setVisibility(View.GONE);
                view_order.setVisibility(View.VISIBLE);
                offer_status.setText("已同意");
                offer_status.setTextColor(Color.parseColor("#06C764"));
                break;

            //未同意
            case "5":
                right_btn.setVisibility(View.GONE);
                view_order.setVisibility(View.GONE);
                offer_status.setText("未同意");
                offer_status.setTextColor(Color.parseColor("#FFC000"));
                break;

            default:
                right_btn.setVisibility(View.GONE);
                offer_status.setText("");
                view_order.setVisibility(View.GONE);
                break;
        }

        //如果报价单位类型数据获取不到，则不处理该条数据
        if (TextUtils.isEmpty(entity.getOfferType())) {
            return;
        }
        String offerType = entity.getOfferType();
        offer_status.setVisibility(View.VISIBLE);
        String title = "";
        String name = "";
        String address = "";
        switch (offerType) {
            case "1"://企业
                address_hint.setText("地址");
                car_info_layout.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(entity.getCompanyTeamAddress())) {
                    address = entity.getCompanyTeamAddress();
                }

                title = !TextUtils.isEmpty(entity.getCompanyName()) ? entity.getCompanyName() : "/";
                name = entity.getCompanyName();

                if (entity.getIsVoluntarily() == 2) {//接单
                    car_iv.setImageResource(R.drawable.icon_order_company_tint_green);
                } else if (entity.getIsVoluntarily() == 0) {//报价
                    if (entity.getPriceSection() != null) {
                        switch (entity.getPriceSection()) {
                            case 1:
                                car_iv.setImageResource(R.drawable.icon_quote_company_tint_red);
                                break;
                            case 2:
                            default:
                                car_iv.setImageResource(R.drawable.icon_quote_company_dark_red);
                                break;
                            case 3:
                            case 5:
                                car_iv.setImageResource(R.drawable.icon_quote_company_tint_green);
                                break;
                            case 4:
                                car_iv.setImageResource(R.drawable.icon_quote_company_dark_green);
                                break;
                            case 6:
                                car_iv.setImageResource(R.drawable.icon_quote_company_gray);
                                break;
                        }
                    } else {//默认深红
                        car_iv.setImageResource(R.drawable.icon_quote_company_dark_red);
                    }
                }
                break;

            case "2"://团队
                address_hint.setText("团队地址");
                car_info_layout.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(entity.getCompanyTeamAddress())) {
                    address = entity.getCompanyTeamAddress();
                }

                title = !TextUtils.isEmpty(entity.getTeamName()) ? entity.getTeamName() : "/";
                name = entity.getTeamName();

                if (entity.getIsVoluntarily() == 2) {//接单
                    car_iv.setImageResource(R.drawable.icon_order_team_tint_green);
                } else if (entity.getIsVoluntarily() == 0) {//报价
                    if (entity.getPriceSection() != null) {
                        switch (entity.getPriceSection()) {
                            case 1:
                                car_iv.setImageResource(R.drawable.icon_quote_team_tint_red);
                                break;
                            case 2:
                            default:
                                car_iv.setImageResource(R.drawable.icon_quote_team_dark_red);
                                break;
                            case 3:
                            case 5:
                                car_iv.setImageResource(R.drawable.icon_quote_team_tint_green);
                                break;
                            case 4:
                                car_iv.setImageResource(R.drawable.icon_quote_team_dark_green);
                                break;
                            case 6:
                                car_iv.setImageResource(R.drawable.icon_quote_team_gray);
                                break;
                        }

                    } else {//默认深红
                        car_iv.setImageResource(R.drawable.icon_quote_team_dark_red);
                    }
                }
                break;

            case "3"://个人
                address_hint.setText("车辆位置");
                if (!TextUtils.isEmpty(entity.getDetailAddress())) {
                    address = entity.getDetailAddress();
                }
                String carInfo = "";
                if (!TextUtils.isEmpty(entity.getCarTypeName()))
                    carInfo += entity.getCarTypeName() + " ";
                if (!TextUtils.isEmpty(entity.getCarLenName()))
                    carInfo += "车长" + entity.getCarLenName() + " ";
                if (!TextUtils.isEmpty(entity.getHeightHurdle()))
                    carInfo += "栏高" + NumberUtil.trim0(entity.getHeightHurdle()) + "米 ";
                car_info.setText(TextUtils.isEmpty(carInfo) ? "/" : carInfo);
                car_info_layout.setVisibility(View.VISIBLE);

                title = !TextUtils.isEmpty(entity.getCarNumber()) ? entity.getCarNumber() : "/";
                name = entity.getName();

                if (entity.getIsVoluntarily() == 2) {//接单
                    car_iv.setImageResource(R.drawable.icon_order_car_tint_green);
                } else if (entity.getIsVoluntarily() == 0) {//报价
                    if (entity.getPriceSection() != null) {
                        switch (entity.getPriceSection()) {
                            case 1:
                                car_iv.setImageResource(R.drawable.icon_quote_car_tint_red);
                                break;
                            case 2:
                            default:
                                car_iv.setImageResource(R.drawable.icon_quote_car_dark_red);
                                break;
                            case 3:
                            case 5:
                                car_iv.setImageResource(R.drawable.icon_quote_car_tint_green);
                                break;
                            case 4:
                                car_iv.setImageResource(R.drawable.icon_quote_car_dark_green);
                                break;
                            case 6:
                                car_iv.setImageResource(R.drawable.icon_quote_car_gray);
                                break;
                        }

                    } else {//默认深红
                        car_iv.setImageResource(R.drawable.icon_quote_car_dark_red);
                    }
                }
                break;
        }
        owner_name.setText(!TextUtils.isEmpty(title) ? title : "/");
        position_info.setText(!TextUtils.isEmpty(address) ? address : "/");

        String finalName = name;
        right_btn.setOnClickListener(v -> showOfferDialog(entity, offerOrReceive, finalName));
        view_order.setOnClickListener(v -> skipOrder(entity, offerOrReceive));
    }

    /**
     * 在线交流
     *
     * @param entity
     */
    private void gotoExchange(OrderQuoteEntity entity) {
        if (isLogin()) {
            if (entity != null && !TextUtils.isEmpty(entity.getImAccount()) && onTabClickListener != null) {
                onTabClickListener.onChat(entity.getImAccount());
            }
        } else {
            VerificationCodeLoginActivity.start(context);
        }
    }

    /**
     * 拨号检查
     *
     * @param entity
     */
    private void checkCanCall(OrderQuoteEntity entity) {
        if (!isLogin()) {
            VerificationCodeLoginActivity.start(context);
            return;
        }
        if (!TextUtils.isEmpty(entity.getTelphone())) {
            showCallDialog(entity.getTelphone());
        } else {
            ToastUtil.show(context, "无联系方式");
        }
    }

    private boolean isLogin() {
        return !TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""));
    }

    /**
     * 拨打电话对话框
     *
     * @param number
     */
    private void showCallDialog(String number) {
        new RoundDialog.Builder(context)
                .title("确认呼叫")
                .content(number)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(new RoundDialog.SingleCallback() {
                    @Override
                    public void onClick(View v) {
                        callPhone(number);
                    }
                })
                .show();
    }

    /**
     * 展示同意报价对话框
     *
     * @param entity
     * @param type   0-报价，2-接单
     * @param name   报价方名字
     */
    private void showOfferDialog(OrderQuoteEntity entity, int type, String name) {
        String title;
        if (type == 0) {
            title = String.format("您确定要同意%s的报价吗？确定后将生成竞价订单", TextUtils.isEmpty(name) ? "***" : name);
        } else {
            title = String.format("您确定要同意由%s接单吗？确定后将生成竞价订单", TextUtils.isEmpty(name) ? "***" : name);
        }
        new RoundDialog.Builder(context)
                .title("提示")
                .content(title)
                .cancel("取消")
                .confirm("确定")
                .contentGravity(Gravity.CENTER)
                .cancelable(false)
                .confirmCallback(v -> {
                    if (onTabClickListener != null)
                        onTabClickListener.onAgreeClick(entity);
                })
                .show();
    }

    /**
     * 跳转竞价订单详情
     *
     * @param entity
     * @param type   0-报价，2-接单
     */
    private void skipOrder(OrderQuoteEntity entity, int type) {
        if (!TextUtils.isEmpty(entity.getOrderNo())) {
            //跳转竞价订单详情(该页面进入的为货主身份)
            BiddingOrderDetailsActivity.start(context, entity.getOrderNo(), 0);
        }
    }

    protected void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        context.startActivity(intent);
    }


    /**
     * 对字符加星号处理：除前面几位和后面几位外，其他的字符以星号代替
     *
     * @param content  传入的字符串
     * @param frontNum 保留前面字符的位数
     * @param endNum   保留后面字符的位数
     * @return 带星号的字符串
     */
    public static String replaceString2Star(String content, int frontNum, int endNum) {
        if (content == null || content.trim().isEmpty())
            return "";
        int len = content.length();

        if (frontNum >= len || frontNum < 0 || endNum >= len || endNum < 0)
            return content;

        if (frontNum + endNum >= len)
            return content;

        int beginIndex = frontNum;
        int endIndex = len - endNum;
        char[] cardChar = content.toCharArray();

        for (int j = beginIndex; j < endIndex; j++) {
            cardChar[j] = '*';
        }

        return new String(cardChar);
    }
}
